<template>
    <div class="news-setting-container">
        <!-- 步骤导航 -->
        <div class="publish-steps">
            <div class="step-item">
                <div class="step-number">1</div>
                <div class="step-name">待发布内容</div>
            </div>
            <div class="step-line"></div>
            <div class="step-item active">
                <div class="step-number">2</div>
                <div class="step-name">发布设置</div>
            </div>
        </div>

        <!-- 发布设置表单 -->
        <el-form ref="settingForm" :model="form" :rules="rules" label-width="80px" class="setting-form">
            <el-form-item label="标题" prop="title">
                <el-input v-model="form.title" maxlength="100" show-word-limit placeholder="请输入标题" />
            </el-form-item>

            <el-form-item label="封面摘要" prop="abstract">
                <div class="cover-abstract">
                    <el-upload 
                        class="cover-upload" 
                        action="#" 
                        list-type="picture" 
                        :limit="1"
                        :on-change="handleCoverUpload" 
                        :on-remove="handleCoverRemove" 
                        accept="image/*"
                        :file-list="coverFileList" 
                        :show-file-list="false"
                        :auto-upload="false"  
                        :http-request="handleHttpRequest"  
                    >
                        <template #default>
                            <!-- 增加 coverFileList 存在性判断 -->
                            <div v-if="!coverFileList || coverFileList.length === 0" class="upload-placeholder">
                                <el-button size="small" type="primary">+ 上传图片</el-button>
                                <div class="upload-tip">图片信息<br>图片尺寸480*200</div>
                            </div>
                            <img v-else class="uploaded-img" :src="coverFileList[0].url" alt="封面">
                        </template>
                    </el-upload>
                    <el-input type="textarea" v-model="form.abstract" :rows="4" placeholder="请输入摘要" />
                </div>
            </el-form-item>

            <el-form-item label="发送时间" prop="sendTimeType">
                <el-radio-group v-model="form.sendTimeType">
                    <el-radio label="immediate">立即发送</el-radio>
                    <el-radio label="scheduled">定时发送</el-radio>
                </el-radio-group>
                <el-date-picker 
                    v-if="form.sendTimeType === 'scheduled'" 
                    v-model="form.scheduledTime" 
                    type="datetime"
                    placeholder="选择定时发送时间" 
                    style="margin-top: 10px" 
                    :required="form.sendTimeType === 'scheduled'" 
                />
            </el-form-item>
        </el-form>

        <!-- 底部操作按钮 -->
        <div class="setting-actions">
            <el-button @click="handlePrevStep">上一步</el-button>
            <el-button type="primary" @click="handlePublish">发布</el-button>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const settingForm = ref(null)

// 表单数据
const form = reactive({
    title: '',
    cover: '', // 存储 base64 格式图片
    abstract: '',
    sendTimeType: 'immediate', // 默认选中“立即发送”
    scheduledTime: ''
})

// 🌟 确保 coverFileList 初始化为空数组（关键修复）
const coverFileList = ref([])

// 表单验证规则
const rules = {
    title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
    abstract: [{ required: true, message: '请输入摘要', trigger: 'blur' }],
    sendTimeType: [{ required: true, message: '请选择发送时间类型', trigger: 'change' }],
    scheduledTime: [{ 
        required: () => form.sendTimeType === 'scheduled', 
        message: '请选择定时发送时间', 
        trigger: 'change' 
    }]
}

// 初始化：从本地存储接收待发布列表参数
onMounted(() => {
    try {
        const listStr = localStorage.getItem('tempPublishList')
        if (listStr) {
            const publishList = JSON.parse(listStr)
            // 增加 publishList 存在性判断
            if (publishList && publishList.length > 0) {
                form.title = publishList[0].title || ''
                form.abstract = publishList[0].abstractReal || ''
            }
        }
    } catch (error) {
        console.error('初始化数据失败:', error)
        ElMessage.error('初始化数据失败，请刷新页面重试')
    }
})

// 封面上传：转为 base64 存储
const handleCoverUpload = (file) => {
    try {
        if (!file || !file.raw) {
            ElMessage.error('请上传有效的本地图片文件')
            return
        }

        const reader = new FileReader()
        reader.onload = (e) => {
            const base64Url = e.target.result
            // 确保 coverFileList 是数组再操作（关键修复）
            if (Array.isArray(coverFileList.value)) {
                coverFileList.value = [{ url: base64Url, name: '' }]
            } else {
                coverFileList.value = [{ url: base64Url, name: '' }]
            }
            form.cover = base64Url
            ElMessage.success('封面上传成功')
        }
        reader.onerror = () => {
            ElMessage.error('图片转换失败，请重新上传')
        }
        reader.readAsDataURL(file.raw)
    } catch (error) {
        console.error('上传图片失败:', error)
        ElMessage.error('上传图片失败，请重试')
    }
}

// 封面移除：清空预览和表单数据
const handleCoverRemove = () => {
    // 确保 coverFileList 是数组再操作
    if (Array.isArray(coverFileList.value)) {
        coverFileList.value = []
    } else {
        coverFileList.value = []
    }
    form.cover = ''
    ElMessage.success('封面已移除')
}

// 上一步：返回待发布内容页面
const handlePrevStep = () => {
    router.push({ name: 'newsPublish' })
}

// 发布逻辑：存储 base64 图片+数据到本地，跳转至已发布页面
const handlePublish = () => {
    if (!settingForm.value) return // 增加表单实例存在性判断

    settingForm.value.validate((valid) => {
        if (valid) {
            try {
                const newNews = {
                    id: 'new_' + Date.now(),
                    title: form.title,
                    abstractReal: form.abstract,
                    // 处理封面图（默认空字符串）
                    coverImage: form.cover || '',
                    newsTime: form.sendTimeType === 'scheduled' 
                        ? form.scheduledTime 
                        : new Date().toISOString().slice(0, 19).replace('T', ' '),
                    isPublished: 1,
                    modifiedNewsTime: null
                }

                // 读取已有本地发布数据
                let publishedData = localStorage.getItem('publishedNews')
                publishedData = publishedData ? JSON.parse(publishedData) : []
                // 确保是数组再操作
                if (Array.isArray(publishedData)) {
                    publishedData.unshift(newNews)
                } else {
                    publishedData = [newNews]
                }
                localStorage.setItem('publishedNews', JSON.stringify(publishedData))

                ElMessage.success('发布成功！')
                router.push({ name: 'publishedNews' })
            } catch (error) {
                console.error('发布失败:', error)
                ElMessage.error('发布失败，请重试')
            }
        }
    })
}

// 覆盖默认上传方法，阻止实际请求
const handleHttpRequest = () => {}
</script>

<style scoped>
/* 保持原有样式不变 */
.news-setting-container {
    padding: 24px;
    background-color: #fff;
    min-height: 100vh;
}

.publish-steps {
    display: flex;
    align-items: center;
    margin-bottom: 30px;
    padding-left: 20px;
}

.step-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
}

.step-number {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    background-color: #409eff;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    margin-bottom: 8px;
}

.step-item:not(.active) .step-number {
    background-color: #e5e6eb;
    color: #86909c;
}

.step-name {
    font-size: 14px;
    color: #303133;
}

.step-item:not(.active) .step-name {
    color: #86909c;
}

.step-line {
    flex: 1;
    height: 2px;
    background-color: #e5e6eb;
    margin: 0 15px;
}

.step-item.active~.step-line {
    background-color: #409eff;
}

.setting-form {
    max-width: 800px;
    margin: 0 auto;
}

.cover-abstract {
    display: flex;
    gap: 20px;
}

.cover-upload {
    width: 160px;
    height: 100px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border: 1px dashed #dcdcdc;
    border-radius: 6px;
    cursor: pointer;
    background-color: #f9f9f9;
    transition: border-color 0.2s;
    overflow: hidden; 
}

.cover-upload:hover {
    border-color: #409eff;
}

.upload-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
}

.upload-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 8px;
    text-align: center;
}

.uploaded-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.setting-actions {
    display: flex;
    justify-content: center;
    gap: 10px;
    margin-top: 30px;
}
</style>